module.exports = (_options, _app) => {
  return async function Authentications(_ctx, _next) {
    if (_options.find(v => v == _ctx.request.path) || _ctx.request.path.startsWith('/swagger')) {
      await _next()
    } else {
      const { authorization = '' } = _ctx.header;
      let token = authorization.replace('Bearer ', '');
      if (!token) {
        _ctx.body = await _ctx.response.msg(200, 304, '您没有登录', []);
        return
      }
      try {
        _ctx.validate({
          name: { type: 'string', required: true },
          userId: { type: 'string', required: true },
        }, _ctx.request.body)
        _ctx.app.jwt.verify(token, _app.config.jwt.secret)
      } catch (err) {
        _ctx.helper.log('W', err)
        _ctx.body = await _ctx.response.msg(200, 305, err.name === 'TokenExpiredError' ? 'token 已过期! 请重新获取令牌' : 'Token 令牌不合法!', []);
        return
      }
      if (!await _ctx.service.common.check(_ctx.request.body.userId, _ctx.request.body.name)) {
        _ctx.body = _ctx.response.msg(200, 304, 'token 已过期! 请重新获取令牌', []);
        return
      }
      await _next()
    }
  }
}; 
